/*
 * @lc app=leetcode.cn id=150 lang=cpp
 *
 * [150] 逆波兰表达式求值
 */

// @lc code=start
class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        //类似 1047, 当遇到运算符时, 需要与前面两个数进行计算
        // ["2","1","+","3","*"]
        // [2, 1, + ---> [3, ..
        // [3, 3, * ---> [9, ..
        
        //消消乐。。。。

        std::unordered_map<std::string, std::function<int(int, int)>> operators = {
            {"+", [](int a, int b){ return a + b; }},
            {"-", [](int a, int b){ return a - b; }},
            {"*", [](int a, int b){ return a * b; }},
            {"/", [](int a, int b){ return a / b; }}
        };

        std::stack<std::string> st;
        for (const auto& t : tokens) {
            if (operators.find(t) == operators.end())
                st.push(t);

            else {
                int r, l;
                std::istringstream iss(st.top());
                iss >> r;
                st.pop();

                iss = std::istringstream(st.top());
                iss >> l;
                st.pop();

                int result = operators[t](l, r);
                std::ostringstream oss;
                oss << result;
                st.push(oss.str());    
            }
        }


        int result;
        std::istringstream iss(st.top());
        iss >> result;
        return result;
    }
};
// @lc code=end

